package com.guardchina.framework.util.gson;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * 描述：时间序列化
 *
 * @author lwb
 * @date 2019/3/21 11:35
 */
public class LocalTimeSerializer implements JsonSerializer<LocalTime>, JsonDeserializer<LocalTime> {

    private String timePattern;

    public LocalTimeSerializer(String pattern){
        this.timePattern = pattern;
    }

    @Override
    public JsonElement serialize(LocalTime src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src.format(DateTimeFormatter.ofPattern(timePattern)));
    }

    @Override
    public LocalTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        String time = json.getAsJsonPrimitive().getAsString();
        return LocalTime.parse(time, DateTimeFormatter.ofPattern(timePattern));
    }
}
